<?php
class stYoutubeToolboxvideo_model extends stmodel_2_1{

    public function __construct($config) {
        parent::__construct ( $config );
        $this->setTableName($this->prefix.'st_youtubevideo');
        $this->setPrimaryKey('id');
    }

    public function updateVideo($post, $editPerm = '') {
        $data = $post;
        $playlists = $data['playlist'];
        $video_id = $data['video_id'];
        
        unset($data['playlist']);
        if($editPerm != 'disabled')
            $this->saveRecords($data);

        $stYoutubeToolbox_playlist_video_model = $this->loadmodel ( "stYoutubeToolbox_playlist_video" );

        $args = array();
        //$args['fields'] = array('playlist_id');
        $args['where'] = " video_id like('$video_id')";
        $results = $stYoutubeToolbox_playlist_video_model->getRecords($args);
        $playlist_old = array();
        foreach ($results as $result) {
            $playlist_old[]= $result->playlist_id;
            if(!in_array($result->playlist_id, $playlists)){
                $stYoutubeToolbox_playlist_video_model->deleteRecords($result->id);
            }
        }

        
        $data = array();
        $playlist_insert = array_diff($playlists,$playlist_old);
        $i = 0;
        if(count($playlist_insert)>0){
            foreach ($playlist_insert as $playlist) {
                $data[$i]['id'] = NULL;
                $data[$i]['video_id'] = $video_id;
                $data[$i]['playlist_id'] = $playlist;
                $i++;
            }
        }
        if(count($data)>0)
            $stYoutubeToolbox_playlist_video_model->inserRecords($data);
    }
        
    public function savestYoutubeToolboxVideo($videoFeed, $favorite = 0) {
        $time = date_i18n('Y-m-d H:i:s');
        $dataInsert = array();
        $dataUpdate = array();
        $i=0;
        $user_id = $videoFeed['user_id'];

        $videoFeeds = $videoFeed['video_entry'];
        foreach ($videoFeeds as $videoEntry) {
            $id = $this->getId($videoEntry->getVideoId());
            
            if($id){
                $dataUpdate[$i]['id'] = $id;
                $dataUpdate[$i]['user_id'] = $user_id;
                $dataUpdate[$i]['video_id'] = $videoEntry->getVideoId();
                $dataUpdate[$i]['title'] = $videoEntry->getVideoTitle();
                $dataUpdate[$i]['description'] = $videoEntry->getVideoDescription();
                $dataUpdate[$i]['category'] = $videoEntry->getVideoCategory();
                $tags = (array)$videoEntry->getVideoTags();
                $tag = array();
                foreach ($tags as $value) {
                    $tag[] = $value;
                }
                $tag = implode('|*|', $tag);
                $dataUpdate[$i]['tag'] = $tag;

                $dataUpdate[$i]['duration'] = $videoEntry->getVideoDuration();
                $dataUpdate[$i]['view_count'] = $videoEntry->getVideoViewCount();

                $ratings = (array)$videoEntry->getVideoRatingInfo();
                $rating = array();
                foreach ($ratings as $value) {
                    $rating[] = $value;
                }
                $rating = implode('|*|', $rating);
                $dataUpdate[$i]['rating'] = $rating;

                $dataUpdate[$i]['geo_location'] = $videoEntry->getVideoGeoLocation();
                $dataUpdate[$i]['record_on'] = $videoEntry->getVideoRecorded();

                $videoThumbnails = $videoEntry->getVideoThumbnails();
                $dataUpdate[$i]['thumbnail_url'] = $videoThumbnails[1]['url'];
                $dataUpdate[$i]['youtube_user'] = '';
                $dataUpdate[$i]['favorite'] = $favorite;
//                $edit_url = $videoEntry->getEditLink()->getHref();
                
                if($videoEntry->getEditLink() !== null){
                    $dataUpdate[$i]['can_delete'] = 1;
                }else{
                    $dataUpdate[$i]['can_delete'] = 0;
                }
            }else{
                $dataInsert[$i]['id'] = 'NULL';
                $dataInsert[$i]['user_id'] = $user_id;
                $dataInsert[$i]['cdate'] = $time;
                $dataInsert[$i]['video_id'] = $videoEntry->getVideoId();
                $dataInsert[$i]['title'] = $videoEntry->getVideoTitle();
                $dataInsert[$i]['description'] = $videoEntry->getVideoDescription();
                $dataInsert[$i]['category'] = $videoEntry->getVideoCategory();

                $tags = (array)$videoEntry->getVideoTags();
                $tag = array();
                foreach ($tags as $value) {
                    $tag[] = $value;
                }
                $tag = implode('|*|', $tag);
                $dataInsert[$i]['tag'] = $tag;

                $dataInsert[$i]['duration'] = $videoEntry->getVideoDuration();
                $dataInsert[$i]['view_count'] = $videoEntry->getVideoViewCount();

                $ratings = (array)$videoEntry->getVideoRatingInfo();
                $rating = array();
                foreach ($ratings as $value) {
                    $rating[] = $value;
                }
                $rating = implode('|*|', $rating);
                $dataInsert[$i]['rating'] = $rating;

                $dataInsert[$i]['geo_location'] = $videoEntry->getVideoGeoLocation();
                $dataInsert[$i]['record_on'] = $videoEntry->getVideoRecorded();

                $videoThumbnails = $videoEntry->getVideoThumbnails();
                $dataInsert[$i]['thumbnail_url'] = $videoThumbnails[1]['url'];
                $dataInsert[$i]['youtube_user'] = '';
                $dataInsert[$i]['favorite'] = $favorite;
//                $edit_url = $videoEntry->getEditLink()->getHref();
                if($videoEntry->getEditLink() !== null){
                    $dataUpdate[$i]['can_delete'] = 1;
                }else{
                    $dataUpdate[$i]['can_delete'] = 0;
                }
            }
            $i++;
        }
        $this->inserRecords($dataInsert) ;
        $this->updateRecords($dataUpdate);
        
    }

    public function inserRecords($data = '', $where = ''){
        if(count($data)>0){
            $query = "INSERT INTO $this->_tableName
                    ( id, user_id, video_id, youtube_user, title, description, category, tag, duration, view_count, rating
                    , geo_location, record_on, thumbnail_url, cdate, favorite, can_delete )
                    VALUES
                    ";
            $query1 = array();
            foreach ($data as $value) {
                $query1[] = $this->prepare("(%d, %d, %s, %s, %s, %s, %s, %s, %s, %d, %s, %s, %s, %s, %s, %d, %d)",
                        $value['id'], $value['user_id'], $value['video_id'], $value['youtube_user'], $value['title']
                        , $value['description'], $value['category'], $value['tag'], $value['duration']
                        , $value['view_count'], $value['rating'], $value['geo_location'], $value['record_on']
                        , $value['thumbnail_url'], $value['cdate'], $value['favorite'], $value['can_delete']
                        );
            }
            $query1 = implode(', ', $query1);
            $query .= ' '.$query1;
//            echo $query;
            return $this->query( $query );
        }else{
            return false;
        }
    }

    public function updateRecords($data = '', $where = ''){
        if(count($data)>0){
            foreach ($data as $value) {                
                $where = array($this->_primaryKey => $value[$this->_primaryKey]);
                $this->update($this->_tableName, $value, $where);
            }
        }
        return false;
    }

    public function getId($videoId){
        $query = "SELECT id
        FROM $this->_tableName
        WHERE video_id like ('$videoId')
        ";
        $result = $this->get_var($query);
        return $result;
    }

    public function getRecords($args = '') {
        $default_args = array(
            'fields' => '*',
            'and_where' => '',
            'or_where' => '',
            'where' => '',
            'order' => '',
            'limit' => '',
            'group_by' => '',
            'custom_query' => '',
        );
        if ($args == '')
            $args = $default_args;

        $fields = $args['fields'] ? $args['fields'] : '*';
        $and_where = $args['and_where'] ? $args['and_where'] : '';
        $or_where = $args['or_where'] ? $args['or_where'] : '';
        $custom_where = $args['where'] ? $args['where'] : '';
        $order = $args['order'] ? $args['order'] : '';
        $limit = $args['limit'] ? $args['limit'] : '';
        $group_by = $args['group_by'] ? $args['group_by'] : '';
        $custom_query = $args['custom_query'] ? $args['custom_query'] : '';
        if (!empty($custom_query)) {
            $query = $custom_query;
        } else {
            if ($fields != '*')
                $fields = implode(', ', $fields);
            //
            $where = ' WHERE ';

            if ($and_where != '')
                $where .= implode('', $and_where);
            if ($or_where != '')
                $where .= implode('', $or_where);
            if ($custom_where != '')
                $where .= $custom_where;
            if ($where == ' WHERE ')
                $where = '';
            //
            if ($order != '')
                $order = ' ORDER BY ' . implode(' ', $order);
            //
            if ($limit != '')
                $limit = ' LIMIT ' . implode(', ', $limit);
            if ($group_by != '')
                $group_by = ' GROUP BY ' . $group_by;
            //

            $table_playlist = $this->prefix.'st_youtubeplaylist';
            $table_playlist_video = $this->prefix.'st_youtube_playlist_video';
            $table_user = $this->prefix.'st_youtube_user';
            $query = "SELECT $fields
            FROM $this->_tableName video
            LEFT JOIN $table_playlist_video playlist_video on playlist_video.video_id = video.video_id
            LEFT JOIN $table_playlist playlist on playlist.playlist_id = playlist_video.playlist_id
            INNER JOIN $table_user user on user.id = video.user_id
            $where
            $group_by
            $order
            $limit
            ";
        }
//        echo $query;
        return $this->get_results($query);
    }

    public function deleteRecords($id = '') {
        require_once $this->config['pluginDir'].'stYoutubeToolboxclass.php';
        $stYoutubeToolbox = new stYoutubeToolboxclass($this->config, $this->option);

        $args = array();
        $args['fields'] = array("video.*, playlist.name playlist_name, playlist.playlist_id playlist_id");
        $args['where'] = " video.id = $id";
        $results = $this->getRecords($args);
        $result = $results[0];
        $video_id = $result->video_id;

        if($result->can_delete){
            $stYoutubeToolbox->deleteVideo($video_id);
        }else{
            $stYoutubeToolbox->removeFavorite($video_id);
        }
        

        $stYoutubeToolbox_playlist_video_model = $this->loadmodel ( "stYoutubeToolbox_playlist_video" );
        $args['where'] = " video_id like('$video_id')";
        $results = $stYoutubeToolbox_playlist_video_model->getRecords($args);
        foreach ($results as $result) {
            $stYoutubeToolbox_playlist_video_model->deleteRecords($result->id);
        }
        parent::deleteRecords($id);
        return true;
    }

    public function countRecords($args = ''){        
        
        $result = $this->getRecords($args);        
        return count($result);
        
    }

    public function getUserId($videoId){
        $query = "SELECT user_id
        FROM $this->_tableName
        WHERE video_id like ('$videoId')
        ";
        $result = $this->get_var($query);
        return $result;
    }
}